<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchIntercityOrderListAPI } from '@/apis/fetchIntercityOrderList'
import { IntercityOrderStatus, OrderStatus, getIntercityOrderStatusString, getIntercityOrderTypeString, getOrderStatusString, getOrderTypeString } from '@/types/enum'
import type { IntercityOrder, LoadMoreData, NormalOrder } from '@/types/api'
import { useUserInfoStore } from '@/store/userInfo'
import { useGeneralConfigStore } from '@/store/generalConfig'
import { useOrdersTabSelectionStore } from '@/store/ordersTabSelection'
import { fetchOrderListAPI } from '@/apis/fetchOrderList'
import { fetchCommentDetailAPI } from '@/apis/fetchCommentDetail'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const generalConfigStore = useGeneralConfigStore()

/* ------------------------------ 自定义导航栏 START ------------------------------ */
// 是否显示状态栏背景
const isShowNavBg = ref(false)
// 监听页面滚动，更新状态栏背景可见性
onPageScroll((e) => {
  const toggle = useThrottleFn(() => isShowNavBg.value = e.scrollTop > 16, 100)
  toggle()
})
// 将导航栏背景可见性提供给导航栏组件
provide(isShowNavigationBarBackgroundKey, isShowNavBg)
/* ------------------------------- 自定义导航栏 END ------------------------------- */

/* ------------------------------- 页面状态 START ------------------------------- */
const ordersTabSelectionStore = useOrdersTabSelectionStore()

// 订单状态列表，遍历对应 enum 的 values，
// 因为 values 中包含字符串(enum key)和数字(enum value)，
// 取数字的部分
const orderStatusList = computed(() => {
  if (ordersTabSelectionStore.selectedSegmentIndex === 0) {
    return Object.values(OrderStatus)
      .filter(el => typeof el === 'number') as OrderStatus[]
  }
  else {
    return Object.values(IntercityOrderStatus)
      .filter(el => typeof el === 'number') as IntercityOrderStatus[]
  }
})

// 每个订单状态对应的 tab 名称
const tabConfiguration = computed(() => {
  if (ordersTabSelectionStore.selectedSegmentIndex === 0) {
    return orderStatusList.value.map((el) => {
      return getOrderStatusString(el as OrderStatus)
    })
  }
  else {
    return orderStatusList.value.map((el) => {
      return getIntercityOrderStatusString(el as IntercityOrderStatus)
    })
  }
})
/* -------------------------------- 页面状态 END -------------------------------- */

/* ------------------------------- 页面数据 START ------------------------------- */
// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<NormalOrder | IntercityOrder>>(
  fetchData,
  {
    manual: true,
    isNoMore: d => d?.list.length === d?.total,
  },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<NormalOrder | IntercityOrder>): Promise<LoadMoreData<NormalOrder | IntercityOrder>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  if (ordersTabSelectionStore.selectedSegmentIndex === 0) {
    const res = await fetchOrderListAPI(
      {
        page: _page.toString(),
        limit: '10',
        status: orderStatusList.value[ordersTabSelectionStore.selectedTabIndex].toString(),
      },
      userInfoStore.userInfo!.token!,
    )
    return {
      list: res.data?.data.data || [],
      page: _page,
      total: res.data?.data.total || 0,
    }
  }
  else {
    const res = await fetchIntercityOrderListAPI(
      {
        page: _page.toString(),
        limit: '10',
        status: orderStatusList.value[ordersTabSelectionStore.selectedTabIndex].toString(),
      },
      userInfoStore.userInfo!.token!,
    )
    return {
      list: res.data?.data.data || [],
      page: _page,
      total: res.data?.data.total || 0,
    }
  }
}

onShow(() => refresh())
/* -------------------------------- 页面数据 END -------------------------------- */

function handleSegmentChange(i: number) {
  ordersTabSelectionStore.selectedSegmentIndex = i
  ordersTabSelectionStore.selectedTabIndex = 0
  refresh()
}

function handleTabChange(i: number) {
  ordersTabSelectionStore.selectedTabIndex = i
  refresh()
}

/**
 * @description 点击订单时触发
 */
function handleTapOrder(id: string) {
  if (ordersTabSelectionStore.selectedSegmentIndex === 0) {
    router.push({
      name: 'orderDetail',
      params: { id },
    })
  }
  else {
    router.push({
      name: 'intercityOrderDetail',
      params: { id },
    })
  }
}

/**
 * @description 点击取消订单时触发。
 *
 * @param id - 要取消订单的 id 。
 */
function handleCancelOrder(id: string) {
  const type = ordersTabSelectionStore.selectedSegmentIndex === 0 ? 'normal' : 'intercity'
  const status = orderStatusList.value[ordersTabSelectionStore.selectedTabIndex].toString()
  router.push({
    name: 'cancelOrder',
    params: { type, id, status },
  })
}

/**
 * @description 点击联系平台时触发。
 */
function handleContactPlatform() {
  uni.makePhoneCall({
    phoneNumber: generalConfigStore.generalConfig?.mobile || '',
  })
}

/**
 * @description 点击联系司机时触发。
 */
function handleContactDriver(mobile?: string) {
  uni.makePhoneCall({
    phoneNumber: mobile || '',
  })
}

function handle110() {
  uni.makePhoneCall({
    phoneNumber: '110',
  })
}

/**
 * @description 点击开发票时触发。
 *
 * @param id - 要开发票的订单的 id。
 * @param money - 开发票的金额，在这里就是要开票的订单的价格
 */
function handleIssueInvoice(id: string, money: string) {
  router.push({
    name: 'invoiceForm',
    params: {
      type: 'intercity',
      ids: id,
      money,
    },
  })
}

/**
 * @description 点击评价司机时触发
 *
 * @param id item 的 id
 */
function handleRateDriver(id: string) {
  router.push({
    name: 'rateDriver',
    params: {
      order_id: id,
    },
  })
}

async function handleViewRate(id: string) {
  const res = await fetchCommentDetailAPI({
    id,
  }, userInfoStore.userInfo!.token)
  if (res.data?.code !== 1) {
    uni.showToast({ title: res.data?.msg, icon: 'none' })
    return
  }
  router.push({
    name: 'rateDriver',
    params: {
      old_data: JSON.stringify(res.data.data),
    },
  })
}
</script>

<template>
  <image
    class="absolute left-0 top-0 h-615rpx w-screen"
    src="@/static/images/order_bg.png"
  />
  <NavigationBar title="订单" front-color="#000000" :is-show-back-button="false" />
  <view class="relative z-1000">
    <!-- 撑出 NavigationBar 的高度 ⬇️ -->
    <Spacer height="44" unit="px" />
    <view class="mx-57rpx">
      <Segment
        :selected-index="ordersTabSelectionStore.selectedSegmentIndex"
        :items="['叫车订单', '城际订单']"
        @change="handleSegmentChange"
      />
    </view>
    <Spacer height="16" />
    <Tabs
      :selected-index="ordersTabSelectionStore.selectedTabIndex"
      :items="tabConfiguration"
      @change="handleTabChange"
    />
    <Spacer height="30" />
  </view>
  <view class="relative z-10">
    <view v-if="dataList.length === 0" class="h-800rpx flex items-center justify-center text-28rpx text-#9999999">
      暂无订单
    </view>
    <view v-else class="px-24rpx">
      <Order
        v-for="item in dataList"
        :key="item.id"
        :title="ordersTabSelectionStore.selectedSegmentIndex === 0 ? '' : getIntercityOrderTypeString(item.type)"
        :type="ordersTabSelectionStore.selectedSegmentIndex === 0 ? 'normal' : 'intercity'"
        :status="(item as IntercityOrder).status || (item as NormalOrder).order_status"
        :created-at="(item as IntercityOrder).start_time"
        :price="item.pay_money"
        :from="item.start_place"
        :to="item.end_place"
        @tap="handleTapOrder(item.id.toString())"
        @on-tap-cancel="handleCancelOrder(item.id.toString())"
        @on-tap-contact-platform="handleContactPlatform"
        @on-tap-contact-driver="handleContactDriver((item as NormalOrder).mobile)"
        @on-tap-issue-invoice="handleIssueInvoice(item.id.toString(), item.pay_money)"
        @on-tap110="handle110"
        @on-tap-cancel-reason="handleTapOrder(item.id.toString())"
        @on-tap-rate-driver="handleRateDriver(item.id.toString())"
        @on-tap-view-rate="handleViewRate(item.id.toString())"
      />
      <uv-load-more
        v-if="dataList.length > 3"
        :status="loadMoreStatus"
        @loadmore="loadMore"
      />
    </view>
  </view>

  <uv-loading-page
    :loading="loading && !loadingMore"
    loading-text="加载中..."
    font-size="28rpx"
    loading-mode="spinner"
  />
</template>

<route lang="yaml">
name: 'orders'
style:
  navigationStyle: 'custom'
</route>
